package com.voice.client.message.impl;

import com.voice.client.AbstractClientImpl;
import com.voice.client.Profile;
import com.voice.client.message.callback.MessageCallback;
import com.voice.client.message.entity.Message;
import com.voice.client.message.StreamClient;
import com.voice.core.connection.Connection;
import com.voice.core.connection.entity.Stream;
import com.voice.core.connection.entity.StreamData;
import com.voice.core.exception.ClientException;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;

@Slf4j
public class StreamClientImpl extends AbstractClientImpl implements StreamClient {

    private MessageCallback callback;

    public StreamClientImpl(Profile profile){
        super(profile);
    }
    @Override
    public void connect(MessageCallback callback) {
        if (this.isConnected.compareAndSet(false, true)) {
            this.setMessageListener(callback);
            doConnect();
        } else {
            throw new ClientException("client is already connected!");
        }
    }

    @Override
    public void setMessageListener(MessageCallback callback) {
        this.callback = callback;
    }

    @Override
    public void onDataRead(Connection connection, Stream stream, StreamData streamData) {
        Message m = this.convertStreamData2Message(streamData);
        CompletableFuture.runAsync(() -> {
            if (callback != null) {
                this.callback.consume(m);
            } else {
                log.warn("no message callback for {}",m);
            }
        });
    }

    @Override
    public String path() {
        return "/device/controller/echo/success";
    }
}
